#include "ChatServer.h"

ChatServer::ChatServer(QObject *parent) : QTcpServer(parent) {
    connect(this, &QTcpServer::newConnection, this, &ChatServer::onNewConnection);
}

void ChatServer::onNewConnection() {
    qDebug() << "A new client has connected.";

    QTcpSocket *clientSocket = nextPendingConnection();
    clients.append(clientSocket);

    connect(clientSocket, &QTcpSocket::readyRead, this, &ChatServer::onReadyRead);
    connect(clientSocket, &QTcpSocket::disconnected, [this, clientSocket]() {
        qDebug() << "A client has disconnected.";
        clients.removeAll(clientSocket);
        clientSocket->deleteLater();
    });
}

void ChatServer::onReadyRead() {
    QTcpSocket *senderSocket = static_cast<QTcpSocket*>(sender());
    QByteArray data = senderSocket->readAll();
    QString message = QString::fromUtf8(data);

    QString clientAddress = senderSocket->peerAddress().toString();
    quint16 clientPort = senderSocket->peerPort();

    qDebug() << "Received from client:" << clientAddress << ":" << clientPort << "Message:" << message;

    for (QTcpSocket *client : clients) {
        if (client != senderSocket) {
            QString fullMessage = QString("[%1:%2] %3").arg(clientAddress).arg(clientPort).arg(message);
            client->write(fullMessage.toUtf8());
        }
    }
}
